package com.googlecode.pdfbricks.cli.parser;

import java.io.File;

import org.apache.commons.cli.CommandLine;

import com.googlecode.pdfbricks.cli.constant.CommandConstant;
import com.googlecode.pdfbricks.cli.constant.OptionConstant;
import com.googlecode.pdfbricks.engine.base.Executable;
import com.googlecode.pdfbricks.merger.MergingBuilder;

/**
 * @author Johny Huang
 * @date 2009-3-13
 */
public class MergeCommandParser implements CommandParser{
	
	private static CommandParser commandParser=new MergeCommandParser();
	
	private MergeCommandParser(){
	}
	
	public static CommandParser getInstance(){
		return commandParser;
	}

	/**
	 * <p>The merge command should has a pattern like </p>
	 * -merge desFilePath [srcFilePath&lt;PageRange,PageRange...&gt;;srcFilePath&lt;&gt;;...]
	 * </br><br/>
	 * <p>PageRange pattern example:
	 * <9,5-14,7-3><br/>
	 * 9 means the page 9.It's a PageRange of single page.<br/>
	 * 5-14 means from page 5(included) to page 14.It's a PageRange in order.<br/>
	 * 7-3 means from page 7(included) to page 3.It's a PageRange in reverse order.<br/>
	 * </p>
	 * 
	 * @param A String array which is split from a command line.
	 * @return
	 */
	public Executable parse(final CommandLine commandLine){
		MergingBuilder builder=null;
		
		if(commandLine==null){
			throw new NullPointerException("CommandLine is null");
		}else{
		    builder=new MergingBuilder();
		}
		
		if(commandLine.hasOption(OptionConstant.FROM.getOpt())){
			String fromCommandStr=commandLine.getOptionValue(OptionConstant.FROM.getOpt());
		    String[] fromPageRangeStrs=fromCommandStr.split(CommandConstant.SEMICOLON);
		    for(int i=0;i<fromPageRangeStrs.length;i++){
		    	builder.from(FilePageRangeParser.getInstance().parse(fromPageRangeStrs[i]));
		    }
		}
		
		if(commandLine.hasOption(OptionConstant.TO.getOpt())){
			builder.to(new File(commandLine.getOptionValue(OptionConstant.TO.getOpt())));
		}
		
		return builder.build();
	}
	
}
